package chen.web.forum;

import chen.web.InitMyContextFilter;
import chen.web.MyContext;
import chen.web.MyContextProvider;
import chen.web.antispam.CaptchaException;
import chen.web.antispam.JudgeStore;
import chen.web.antispam.CaptchaStore;
import chen.web.antispam.CaptchaStore.VerifyResult;
import chen.web.antispam.Characteristic;
import chen.web.antispam.Judge;
import chen.web.antispam.Regulation;

/**
 * 若检测出用户操作不符合规定，则需要判断验证码是否正确，才能继续操作。
 * 这需要在页面输入验证码配合
 * @author chen
 *
 */
public class AntiSpamTopicManager extends BaseTopicManagerProxy implements TopicManager{

	public static final String PostAction = "post";
	
	private CaptchaStore captchaStore;
	public AntiSpamTopicManager(TopicManager tm, JudgeStore anti, CaptchaStore captchaStore) {
		super(tm);
		// TODO Auto-generated constructor stub
		init(anti);
		this.captchaStore = captchaStore;
	}

	@Override
	public Subject post(Subject subject) throws NotLowestException {
		// TODO Auto-generated method stub
		Characteristic ch = Characteristic.newInstance();
		beforePost(ch);
		Subject result = super.post(subject);
		afterPost(ch);
		return result;
	}

	@Override
	public Reply post(Reply reply) {
		// TODO Auto-generated method stub
		Characteristic ch = Characteristic.newInstance();
		beforePost(ch);
		Reply result = super.post(reply);
		afterPost(ch);
		return result;
	}

	private Judge judge;
	private void init(JudgeStore anti){
		judge = anti.createJudge(PostAction, new Regulation(60, 4));
	}
	
	private void beforePost(Characteristic ch){
		MyContext context = MyContextProvider.getMyContext();
		String uuid = context.getUuid();
		String captcha = (String) context.getAttribute(InitMyContextFilter.Captcha_Attribute_Name);
		if(judge.against(ch)){
			VerifyResult result = captchaStore.verify(uuid, captcha);
			if(result != VerifyResult.success)
				throw new CaptchaException(result);
		}
	}
	
	private void afterPost(Characteristic ch){
		judge.record(ch);
	}
	
}
